import { _decorator, Component, Node,instantiate, Prefab, Layout, UITransform, EventTouch,Vec2,Vec3, UIOpacity, director } from 'cc';
import { GameData } from './GameData';
import { Plant } from './Plant';
import { Tile } from './Tile';
const { ccclass, property } = _decorator;
const gameData = GameData.getInstance()

function throttle(func: Function, wait: number) {
    let lastTime = 0;
    return function(...args: any[]) {
        const now = Date.now();
        if (now - lastTime >= wait) {
            lastTime = now;
            func.apply(this, args);
        }
    };
}

@ccclass('PlantMap')
export class PlantMap extends Component {

    @property(Prefab)
    blockPrefab = null // 地图块的预制体

    // 声明属性 children 的 cc 类型为 Node 数组
    @property({
        type: [Prefab]
    })
    plantPrefab: Prefab[] = [];


    @property(Node)
    plantLayer = null; // 植物图层

    canAddPlant = false; // 是否可以添加植物


    createMapGrid(rows: number, cols:number) {
        
        let container = this.node; // 地图容器节点

        for (let i = 0; i < rows; ++i) {
            for (let j = 0; j < cols; ++j) {
                // 实例化地图块
                let block = instantiate(this.blockPrefab);
                block.getComponent(Tile).row = i
                block.getComponent(Tile).col = j
                block.getComponent(UIOpacity).opacity = 0;
                // 将地图块添加到容器中
                container.addChild(block);
            }
        }
    }
    onLoad() {
        this.createMapGrid(5, 9);

        const throttledTouchMove = throttle(this.handleTouch.bind(this), 100); 
        this.node.on(Node.EventType.TOUCH_START, this.handleTouch, this);
        this.node.on(Node.EventType.TOUCH_MOVE, throttledTouchMove, this);
        this.node.on(Node.EventType.TOUCH_END, this.onTouchEnd, this);
    }

    handleTouch(event: EventTouch) {
        // 没有选中类型，不能创建植物
        if(gameData.selectType === -1){
            return
        }
        if (!this.node) {
            return;
        }

        // 获取触摸位置的世界坐标
        const touchPos = event.getUILocation();

        // 将世界坐标转换为节点坐标
        const mapUITransform = this.node.getComponent(UITransform);
        if (mapUITransform) {
            const localPos = mapUITransform.convertToNodeSpaceAR(new Vec3(touchPos.x, touchPos.y, 0));

            // 获取 mapContainer 的 Layout 组件
            const layout = this.node.getComponent(Layout);
            if (layout) {
                // 获取 mapContainer 的子节点
                const children = this.node.children;
                for (const child of children) {
                    const childUITransform = child.getComponent(UITransform);
                    if (childUITransform && childUITransform.getBoundingBox().contains(new Vec2(localPos.x, localPos.y))) {
                        this.highlightNode(child);
                        console.log('触摸到的子节点:', child.getComponent(Tile).row , child.getComponent(Tile).col);
                        // 在这里可以根据子节点的属性进行处理
                        return child;
                    }
                }
            }
        }
        return null
    }

    highlightNode(node) {
        const children = this.node.children;
        for (const child of children) {
            if(child.getComponent(Tile).row === node.getComponent(Tile).row || 
            child.getComponent(Tile).col === node.getComponent(Tile).col){
                child.getComponent(UIOpacity).opacity = 125;
            }else{
                child.getComponent(UIOpacity).opacity = 0;
            }
        }
        node.getComponent(UIOpacity).opacity = 200;
    }

    createPlant(targetNode) {
        // 实例化植物
        let plant = instantiate(this.plantPrefab[gameData.selectType - 1]);
        // 设置植物位置
        plant.setPosition(targetNode.position);
        // 将植物添加到场景中
        this.plantLayer.addChild(plant);
        director.getScene().emit('drop-plant')
        setTimeout(() => { 
            plant.getComponent(Plant).onPlacedByPlayer()
        }, 1000)
    }
    // 手指离开屏幕时调用的方法，可能需要在场景脚本中处理
    onTouchEnd(event: EventTouch) {
        let targetNode = this.handleTouch(event)
        if(targetNode) {
            this.createPlant(targetNode);
        }

        // 取消所有高亮
        this.cancelHighlight();
    }

    cancelHighlight() {
        const children = this.node.children;
        for (const child of children) {
            child.getComponent(UIOpacity).opacity = 0;
        }
    }
}


